library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights2 / N_ind) 


sd(survey_long$feeling_toward)

unique(survey_long$close_relationship2[survey_long$close_num == 5])

survey_long <- survey_long %>% 
  mutate(close_num2 = ifelse(close_relationship2 == "Coworker", 5, close_num), 
         close_num2 = ifelse(close_relationship2 == "Neighbour", 4, close_num2))

########### Regression analyses

m1 <- feols(close_num2 ~ feeling_toward, survey_long,
            cluster = "dem_country_code", weights = survey_long$weights)
m2 <- feols(close_num ~ feeling_toward | dem_country_code, survey_long,
            weights = survey_long$weights)
m3 <- feols(close_num ~ feeling_toward | meta_UUID, survey_long %>% filter(dem_country_code != "US"), 
            weights = survey_long$weights[survey_long$dem_country_code != "US"])

options("modelsummary_format_numeric_latex" = "plain")
models <- list("(1)" = m1, "(2)" = m2, "(3)" = m3)
tab <- modelsummary(models, output = 'tables/TableA7.html', stars = TRUE,
                    coef_rename = c("feeling_toward" = "Feeling", 
                                    "dem_country_code" = "Country-FE", 
                                    "meta_UUID" = "Individual-FE"),
                    coef_omit = c("(Intercept)"),
                    gof_omit = "AIC|BIC|Log|Pseudo|Adj|Within|Std.Errors",
                    statistic = "p.value")
